// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

// reference from github.com/ethereum/go-ethereum/rpc/websocket.go
package rpc

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/caivega/glog"
	"github.com/gorilla/websocket"
	libcore "github.com/tokentransfer/interfaces/core"
	"github.com/tokentransfer/node/consensus"
	"github.com/tokentransfer/node/util"
)

const (
	wsReadBuffer       = 1024
	wsWriteBuffer      = 1024
	wsPingInterval     = 30 * time.Second
	wsPingWriteTimeout = 5 * time.Second
	wsPongTimeout      = 30 * time.Second
	wsDefaultReadLimit = 32 * 1024 * 1024
)

var wsBufferPool = new(sync.Pool)

type WsService struct {
	node     *consensus.Node
	upgrader *websocket.Upgrader
}

func NewWsService(node *consensus.Node) *WsService {
	return &WsService{node: node}
}

func (ws *WsService) Init(c libcore.Config) error {
	allowedOrigins := []string{}
	if util.IsTest() {
		allowedOrigins = append(allowedOrigins, "*")
	}
	ws.upgrader = &websocket.Upgrader{
		ReadBufferSize:  wsReadBuffer,
		WriteBufferSize: wsWriteBuffer,
		WriteBufferPool: wsBufferPool,
		CheckOrigin:     wsHandshakeValidator(allowedOrigins),
	}
	return nil
}

func (ws *WsService) wsService(w http.ResponseWriter, r *http.Request) {
	conn, err := ws.upgrader.Upgrade(w, r, nil)
	if err != nil {
		glog.Debug("WebSocket upgrade failed", "err", err)
		return
	}
	wsc := newWebsocketConn(ws.node, conn, r.Host, r.Header, wsDefaultReadLimit)
	go wsc.process()
}

// wsHandshakeValidator returns a handler that verifies the origin during the
// websocket upgrade process. When a '*' is specified as an allowed origins all
// connections are accepted.
func wsHandshakeValidator(allowedOrigins []string) func(*http.Request) bool {
	origins := make([]string, 0)
	allowAllOrigins := false

	for _, origin := range allowedOrigins {
		if origin == "*" {
			allowAllOrigins = true
		}
		if origin != "" {
			origins = append(origins, origin)
		}
	}
	// allow localhost if no allowedOrigins are specified.
	if len(origins) == 0 {
		origins = append(origins, "http://localhost")
		if hostname, err := os.Hostname(); err == nil {
			origins = append(origins, "http://"+hostname)
		}
	}
	glog.Debug(fmt.Sprintf("Allowed origin(s) for WS RPC interface %v", strings.Join(origins, ", ")))

	f := func(req *http.Request) bool {
		// Skip origin verification if no Origin header is present. The origin check
		// is supposed to protect against browser based attacks. Browsers always set
		// Origin. Non-browser software can put anything in origin and checking it doesn't
		// provide additional security.
		if _, ok := req.Header["Origin"]; !ok {
			return true
		}
		// Verify origin against allow list.
		origin := strings.ToLower(req.Header.Get("Origin"))
		if allowAllOrigins || originIsAllowed(origins, origin) {
			return true
		}
		glog.Warning("Rejected WebSocket connection", "origin", origin)
		return false
	}

	return f
}

func originIsAllowed(allowedOrigins []string, browserOrigin string) bool {
	for _, origin := range allowedOrigins {
		if ruleAllowsOrigin(origin, browserOrigin) {
			return true
		}
	}
	return false
}

func ruleAllowsOrigin(allowedOrigin string, browserOrigin string) bool {
	var (
		allowedScheme, allowedHostname, allowedPort string
		browserScheme, browserHostname, browserPort string
		err                                         error
	)
	allowedScheme, allowedHostname, allowedPort, err = parseOriginURL(allowedOrigin)
	if err != nil {
		glog.Warning("Error parsing allowed origin specification", "spec", allowedOrigin, "error", err)
		return false
	}
	browserScheme, browserHostname, browserPort, err = parseOriginURL(browserOrigin)
	if err != nil {
		glog.Warning("Error parsing browser 'Origin' field", "Origin", browserOrigin, "error", err)
		return false
	}
	if allowedScheme != "" && allowedScheme != browserScheme {
		return false
	}
	if allowedHostname != "" && allowedHostname != browserHostname {
		return false
	}
	if allowedPort != "" && allowedPort != browserPort {
		return false
	}
	return true
}

func parseOriginURL(origin string) (string, string, string, error) {
	parsedURL, err := url.Parse(strings.ToLower(origin))
	if err != nil {
		return "", "", "", err
	}
	var scheme, hostname, port string
	if strings.Contains(origin, "://") {
		scheme = parsedURL.Scheme
		hostname = parsedURL.Hostname()
		port = parsedURL.Port()
	} else {
		scheme = ""
		hostname = parsedURL.Scheme
		port = parsedURL.Opaque
		if hostname == "" {
			hostname = origin
		}
	}
	return scheme, hostname, port, nil
}

type websocketConn struct {
	node *consensus.Node
	conn *websocket.Conn

	wg           sync.WaitGroup
	locker       sync.RWMutex
	pingReset    chan struct{}
	pongReceived chan struct{}
	closeCh      chan interface{}
}

func newWebsocketConn(node *consensus.Node, conn *websocket.Conn, host string, req http.Header, readLimit int64) *websocketConn {
	conn.SetReadLimit(readLimit)
	wc := &websocketConn{
		node:         node,
		conn:         conn,
		pingReset:    make(chan struct{}, 1),
		pongReceived: make(chan struct{}),
		closeCh:      make(chan interface{}),
	}
	// Start pinger.
	conn.SetPongHandler(func(appData string) error {
		select {
		case wc.pongReceived <- struct{}{}:
		case <-wc.closed():
		}
		return nil
	})
	wc.wg.Add(1)
	go wc.pingLoop()
	return wc
}

func (wc *websocketConn) close() {
	wc.wg.Wait()
	close(wc.closeCh)
}

func (wc *websocketConn) closed() <-chan interface{} {
	return wc.closeCh
}

// pingLoop sends periodic ping frames when the connection is idle.
func (wc *websocketConn) pingLoop() {
	var pingTimer = time.NewTimer(wsPingInterval)
	defer wc.wg.Done()
	defer pingTimer.Stop()

	for {
		select {
		case <-wc.closed():
			return

		case <-wc.pingReset:
			if !pingTimer.Stop() {
				<-pingTimer.C
			}
			pingTimer.Reset(wsPingInterval)

		case <-pingTimer.C:
			wc.locker.Lock()
			wc.conn.SetWriteDeadline(time.Now().Add(wsPingWriteTimeout))
			wc.conn.WriteMessage(websocket.PingMessage, nil)
			wc.conn.SetReadDeadline(time.Now().Add(wsPongTimeout))
			wc.locker.Unlock()
			pingTimer.Reset(wsPingInterval)

		case <-wc.pongReceived:
			wc.conn.SetReadDeadline(time.Time{})
		}
	}
}

func (wc *websocketConn) process() {
	defer wc.close()

	for {
		wc.locker.RLock()
		mt, data, err := wc.conn.ReadMessage()
		wc.locker.RUnlock()
		if err != nil {
			glog.Error(err)
			return
		} else if mt == websocket.TextMessage {
			m := &map[string]interface{}{}
			decoder := json.NewDecoder(bytes.NewBuffer(data))
			if err := decoder.Decode(m); err != nil {
				wc.locker.Lock()
				wc.conn.WriteJSON(wrapResult(0, nil, err))
				wc.locker.Unlock()
			} else {
				params := util.ToArray(m, "params")
				id := util.ToUint64(m, "id")
				method := util.ToString(m, "method")

				glog.Infoln("ws", id, method, len(params))
				result, err := wc.node.Call(method, params)
				if err != nil {
					wc.locker.Lock()
					wc.conn.WriteJSON(wrapResult(id, nil, err))
					wc.locker.Unlock()
				} else {
					wc.locker.Lock()
					wc.conn.WriteJSON(wrapResult(id, result, nil))
					wc.locker.Unlock()
				}
				glog.Infoln("response", id, err)
			}
			// Notify pingLoop to delay the next idle ping.
			select {
			case wc.pingReset <- struct{}{}:
			default:
			}
		} else {
			glog.Infoln("ignore websocket message", mt, len(data))
		}
	}
}
